<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="18">
          <h2>算法配置管理</h2>
          <p class="page-description">管理智能排课算法的各种配置参数，支持多种算法类型和自定义参数</p>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增配置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="配置名称" prop="configName">
          <el-input
            v-model="queryParams.configName"
            placeholder="请输入配置名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="算法类型" prop="algorithmType">
          <el-select v-model="queryParams.algorithmType" placeholder="请选择算法类型" clearable>
            <el-option label="遗传算法" value="GENETIC" />
            <el-option label="模拟退火" value="SIMULATED_ANNEALING" />
            <el-option label="粒子群优化" value="PARTICLE_SWARM" />
            <el-option label="禁忌搜索" value="TABU_SEARCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['jwgl:schedule:algorithm:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['jwgl:schedule:algorithm:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['jwgl:schedule:algorithm:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-copy-document"
            size="mini"
            :disabled="single"
            @click="handleCopy"
            v-hasPermi="['jwgl:schedule:algorithm:add']"
          >复制</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['jwgl:schedule:algorithm:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 配置列表 -->
    <el-card>
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="配置ID" align="center" prop="configId" width="80" />
        <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
        <el-table-column label="算法类型" align="center" prop="algorithmType" width="120">
          <template slot-scope="scope">
            <el-tag :type="getAlgorithmTagType(scope.row.algorithmType)">
              {{ getAlgorithmTypeText(scope.row.algorithmType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="种群大小" align="center" prop="populationSize" width="100" />
        <el-table-column label="最大迭代" align="center" prop="maxGenerations" width="100" />
        <el-table-column label="交叉概率" align="center" prop="crossoverRate" width="100" />
        <el-table-column label="变异概率" align="center" prop="mutationRate" width="100" />
        <el-table-column label="默认配置" align="center" prop="isDefault" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isDefault"
              :active-value="1"
              :inactive-value="0"
              @change="handleTableSetDefault(scope.row)"
              :disabled="scope.row.status === '1'"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
              v-hasPermi="['jwgl:schedule:algorithm:query']"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['jwgl:schedule:algorithm:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-copy-document"
              @click="handleCopy(scope.row)"
              v-hasPermi="['jwgl:schedule:algorithm:add']"
            >复制</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['jwgl:schedule:algorithm:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入配置名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法类型" prop="algorithmType">
              <el-select v-model="form.algorithmType" placeholder="请选择算法类型" style="width: 100%">
                <el-option label="遗传算法" value="GENETIC" />
                <el-option label="模拟退火" value="SIMULATED_ANNEALING" />
                <el-option label="粒子群优化" value="PARTICLE_SWARM" />
                <el-option label="禁忌搜索" value="TABU_SEARCH" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种群大小" prop="populationSize">
              <el-input-number
                v-model="form.populationSize"
                :min="10"
                :max="1000"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大迭代次数" prop="maxGenerations">
              <el-input-number
                v-model="form.maxGenerations"
                :min="10"
                :max="10000"
                :step="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交叉概率" prop="crossoverRate">
              <el-input-number
                v-model="form.crossoverRate"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变异概率" prop="mutationRate">
              <el-input-number
                v-model="form.mutationRate"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="精英保留比例" prop="eliteRate">
              <el-input-number
                v-model="form.eliteRate"
                :min="0"
                :max="1"
                :step="0.01"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收敛阈值" prop="convergenceThreshold">
              <el-input-number
                v-model="form.convergenceThreshold"
                :min="0"
                :max="1"
                :step="0.001"
                :precision="3"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否默认配置">
              <el-switch 
                :value="form.isDefault === 1" 
                @input="handleDefaultConfigChange"
                active-text="是" 
                inactive-text="否"
              ></el-switch>
              <div v-if="form.isDefault === 1" class="form-tip">
                <i class="el-icon-warning" style="color: #E6A23C;"></i>
                <span style="color: #E6A23C; font-size: 12px;">设置为默认配置将取消其他配置的默认状态</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">启用</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 配置详情对话框 -->
    <el-dialog title="配置详情" :visible.sync="detailVisible" width="600px" append-to-body @close="handleDetailClose">
      <config-detail v-if="detailVisible && selectedConfigId" :config-id="selectedConfigId" @close="handleDetailClose" @refresh="getList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listAlgorithmConfig,
  getAlgorithmConfig,
  delAlgorithmConfig,
  addAlgorithmConfig,
  updateAlgorithmConfig,
  setDefaultConfig,
  copyAlgorithmConfig,
  exportAlgorithmConfig
} from '@/api/jwgl/algorithmConfig'
import ConfigDetail from './components/ConfigDetail'

export default {
  name: 'AlgorithmConfig',
  dicts: ['sys_normal_disable'],
  components: {
    ConfigDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 算法配置表格数据
      configList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 详情对话框
      detailVisible: false,
      // 选中的配置ID
      selectedConfigId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configName: null,
        algorithmType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        configName: [
          { required: true, message: '配置名称不能为空', trigger: 'blur' },
          { min: 2, max: 100, message: '配置名称长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        algorithmType: [
          { required: true, message: '算法类型不能为空', trigger: 'change' }
        ],
        populationSize: [
          { required: true, message: '种群大小不能为空', trigger: 'blur' },
          { type: 'number', min: 10, max: 1000, message: '种群大小必须在10-1000之间', trigger: 'blur' }
        ],
        maxGenerations: [
          { required: true, message: '最大迭代次数不能为空', trigger: 'blur' },
          { type: 'number', min: 10, max: 10000, message: '最大迭代次数必须在10-10000之间', trigger: 'blur' }
        ],
        crossoverRate: [
          { required: true, message: '交叉概率不能为空', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '交叉概率必须在0-1之间', trigger: 'blur' }
        ],
        mutationRate: [
          { required: true, message: '变异概率不能为空', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '变异概率必须在0-1之间', trigger: 'blur' }
        ],
        eliteRate: [
          { required: true, message: '精英保留比例不能为空', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '精英保留比例必须在0-1之间', trigger: 'blur' }
        ],
        convergenceThreshold: [
          { required: true, message: '收敛阈值不能为空', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '收敛阈值必须在0-1之间', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    detailVisible(newVal) {
      if (!newVal) {
        this.selectedConfigId = null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询算法配置列表 */
    getList() {
      this.loading = true
      listAlgorithmConfig(this.queryParams).then(response => {
        this.configList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        configId: null,
        configName: null,
        algorithmType: null,
        populationSize: 100,
        maxGenerations: 1000,
        crossoverRate: 0.8,
        mutationRate: 0.1,
        eliteRate: 0.1,
        eliteRatio: 0.05,
        convergenceThreshold: 0.001,
        isDefault: 0,
        status: '0',
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId || item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加算法配置'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.configId || row.id || this.ids[0]
      getAlgorithmConfig(id).then(response => {
        this.form = response.data
        // 确保数据类型正确
        if (typeof this.form.isDefault === 'boolean') {
          this.form.isDefault = this.form.isDefault ? 1 : 0
        }
        // 确保id字段正确映射
        if (this.form.configId && !this.form.id) {
          this.form.id = this.form.configId
        } else if (this.form.id && !this.form.configId) {
          this.form.configId = this.form.id
        }
        this.open = true
        this.title = '修改算法配置'
      }).catch(error => {
        this.$modal.msgError('获取配置信息失败')
        console.error('获取配置信息失败:', error)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 确保 isDefault 字段为数字类型
          const formData = { ...this.form }
          if (typeof formData.isDefault === 'boolean') {
            formData.isDefault = formData.isDefault ? 1 : 0
          }
          
          // 确保字段映射正确
          if (formData.configId && !formData.id) {
            formData.id = formData.configId
          } else if (formData.id && !formData.configId) {
            formData.configId = formData.id
          }
          
          if (formData.id != null || formData.configId != null) {
            updateAlgorithmConfig(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addAlgorithmConfig(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.configId || row.id || this.ids
      this.$modal.confirm('是否确认删除算法配置编号为"' + ids + '"的数据项？').then(function() {
        return delAlgorithmConfig(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 复制配置 */
    handleCopy(row) {
      const id = row.configId || row.id || this.ids[0]
      const configName = row.configName || '未知配置'
      
      this.$prompt('请输入新配置名称', '复制配置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: `${configName}_副本`,
        inputPattern: /^.{2,100}$/,
        inputErrorMessage: '配置名称长度在2到100个字符之间'
      }).then(({ value }) => {
        return copyAlgorithmConfig(id, value)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('复制成功')
      }).catch(() => {})
    },
    /** 处理默认配置切换 */
    handleDefaultConfigChange(value) {
      if (value) {
        this.$modal.confirm('设置为默认配置将取消其他配置的默认状态，确认继续？', '设置默认配置', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.isDefault = 1
        }).catch(() => {
          // 用户取消，不改变状态
        })
      } else {
        this.form.isDefault = 0
      }
    },
    /** 表格中设置默认配置 */
    handleTableSetDefault(row) {
      const newDefaultValue = row.isDefault
      const oldDefaultValue = newDefaultValue === 1 ? 0 : 1
      const text = newDefaultValue === 1 ? '设置' : '取消设置'
      
      this.$modal.confirm('确认' + text + '"' + row.configName + '"为默认配置？').then(() => {
        return setDefaultConfig(row.configId || row.id, newDefaultValue)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess(text + '成功')
      }).catch(() => {
        // 操作失败，恢复开关状态
        this.$nextTick(() => {
          row.isDefault = oldDefaultValue
        })
      })
    },
    /** 设置默认配置 */
    handleSetDefault(row) {
      const isCurrentlyDefault = row.isDefault === 1
      const newDefaultValue = isCurrentlyDefault ? 0 : 1
      const text = isCurrentlyDefault ? '取消设置' : '设置'
      
      this.$modal.confirm('确认' + text + '"' + row.configName + '"为默认配置？').then(() => {
        return setDefaultConfig(row.configId || row.id, newDefaultValue)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess(text + '成功')
      }).catch(() => {
        // 不需要恢复状态，因为我们使用 :value 而不是 v-model
      })
    },
    /** 查看详情 */
    handleDetail(row) {
      this.selectedConfigId = row.configId || row.id
      this.detailVisible = true
    },
    /** 关闭详情对话框 */
    handleDetailClose() {
      this.detailVisible = false
      this.selectedConfigId = null
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jwgl/schedule/algorithm/export', {
        ...this.queryParams
      }, `algorithm_config_${new Date().getTime()}.xlsx`)
    },
    /** 获取算法类型标签类型 */
    getAlgorithmTagType(type) {
      const typeMap = {
        'GENETIC': 'success',
        'SIMULATED_ANNEALING': 'warning',
        'PARTICLE_SWARM': 'info',
        'TABU_SEARCH': 'danger'
      }
      return typeMap[type] || 'info'
    },
    /** 获取算法类型文本 */
    getAlgorithmTypeText(type) {
      const typeMap = {
        'GENETIC': '遗传算法',
        'SIMULATED_ANNEALING': '模拟退火',
        'PARTICLE_SWARM': '粒子群优化',
        'TABU_SEARCH': '禁忌搜索'
      }
      return typeMap[type] || type
    }
  }
}
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 500;
  }
  
  .page-description {
    margin: 8px 0 0 0;
    color: #909399;
    font-size: 14px;
  }
}

.search-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.form-tip {
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}
</style>